package com.dyava.dycache.core;

import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.Callable;

public class CacheEngineManager extends CacheEngineContext{

    /**
     * 多id 缓存点
     * @param cacheName  缓存点的名称
     * @param id        缓存点每个数据的id
     * @param nextGetter 的T 必须和 CacheDefined Type保持一致
     * @return
     * @throws Exception
     */
    public <T> T getObject(String cacheName, Object id, Callable<T> nextGetter) {
        id = (id!=null)?id: CacheConstant.NULL;
        CacheDefined cacheDefined = cacheDefinedMap.get(cacheName);
        if(cacheDefined==null){
            throw new CacheRuntimeException(cacheName+"未定义");
        }
        if(cacheDefined.hasVersion){ //有版本信息的，先对比版本
            String firstVersion = firstCacheEngine().getCacheVersion(this,cacheDefined,id);
            CacheEngine lastCacheEngine = lastCacheEngine();
            if(lastCacheEngine!=null){ //如果有最后的引擎，需要对比
                String lastVersion = lastCacheEngine.getCacheVersion(this,cacheDefined,id);
                if(!StringUtils.equals(firstVersion,lastVersion)){
                    firstCacheEngine().deleteCacheChain(this,cacheDefined,id); //版本不一致，全链删除
                }
            }
        }
        CacheWrap cacheWrap = firstCacheEngine().getObjectChain(this,cacheDefined,id,nextGetter);
        if(cacheWrap!=null){
            return (T)cacheWrap.getData();
        }else{
            return null;
        }
    }
    /**
     * 多id 缓存点
     * @param cacheName  缓存点的名称
     * @param id        缓存点每个数据的id
     * @return
     * @throws Exception
     */
    public <T> T getObject(String cacheName, Object id) {
        return getObject(cacheName,id,null);
    }
    /**
     * 无id 独立缓存点
     * @param cacheName  缓存点的名称
     * @param nextGetter 的T 必须和 CacheDefined Type保持一致
     * @return
     * @throws Exception
     */
    public <T> T getObject(String cacheName, Callable<T> nextGetter) {
        return getObject(cacheName,null,nextGetter);
    }
    /**
     * 无id 独立缓存点
     * @param cacheName  缓存点的名称
     * @return
     * @throws Exception
     */
    public <T> T getObject(String cacheName) {
        return getObject(cacheName,null,null);
    }

    /**
     * 删除缓存
     * @param cacheName
     * @param id
     */
    public void deleteObject(String cacheName, Object id){
        id = (id!=null)?id: CacheConstant.NULL;
        CacheDefined cacheDefined = cacheDefinedMap.get(cacheName);
        if(cacheDefined==null){
            throw new CacheRuntimeException(cacheName+"未定义");
        }
        firstCacheEngine().deleteCacheChain(this,cacheDefined,id);
    }

}